package com.fengye.demo.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fengye.demo.entity.SysDept;
import com.fengye.demo.entity.SysRoleDept;
import com.fengye.demo.helper.DataBaseHelper;
import com.fengye.demo.mapper.SysDeptMapper;
import com.fengye.demo.mapper.SysRoleDeptMapper;
import com.fengye.demo.service.RemoteDataScopeService;
import lombok.AccessLevel;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service("sdss")
@RequiredArgsConstructor(access = AccessLevel.PRIVATE)
public class RemoteDataScopeServiceImpl implements RemoteDataScopeService {

    private final SysRoleDeptMapper roleDeptMapper;
    private final SysDeptMapper deptMapper;

    @Override
    public String getRoleCustom(Long roleId) {
        List<SysRoleDept> list = roleDeptMapper.selectList(
                new LambdaQueryWrapper<SysRoleDept>()
                        .select(SysRoleDept::getDeptId)
                        .eq(SysRoleDept::getRoleId, roleId));
        if (CollUtil.isNotEmpty(list)) {
            return list.stream().map(SysRoleDept::getDeptId).map(String::valueOf).collect(Collectors.joining(","));
        }
        return null;
    }

    @Override
    public String getDeptAndChild(Long deptId) {
        List<SysDept> deptList = deptMapper.selectList(new LambdaQueryWrapper<SysDept>()
                .select(SysDept::getDeptId)
                .apply(DataBaseHelper.findInSet(deptId, "ancestors")));

        List<Long> ids = deptList.stream().map(SysDept::getDeptId).collect(Collectors.toList());
        ids.add(deptId);
        if (CollUtil.isNotEmpty(ids)) {
            return ids.stream().map(String::valueOf).collect(Collectors.joining(","));
        }
        return null;
    }

}